import os
import uuid
from django.http import JsonResponse, FileResponse
from rest_framework.views import APIView
from app01 import models
from app01.woutils.response import response
from app01.woutils.user_jwt import ParseToekn
from urllib.parse import quote

path = "app01/media/contracts"
os.makedirs(path, exist_ok=True)

class ImgFileApi(APIView):
    def get(self, request):  # 图片获取显示
        try:
            mode = request.query_params.get("mode")
            mid = request.query_params.get("mid")
            #检查图片是否存在
            obj = models.Contract.objects.filter(mid=mid)
            if obj.exists():
                obj = obj.values()
                file_path = obj[0]['path']
            else:
                return response(503, "未找该图片", "")

            file_name = obj[0]['file_name']
            f = open(file_path, 'rb')

            if mode:
                #下载模式
                r = FileResponse(f, as_attachment=True, filename=f"{quote(file_name)}")
                return r
            else:
                #预览模式
                r = FileResponse(f, as_attachment=False, filename=f"{file_name}")
                return r
        except Exception as e:
            return response(503, "未找到该文件", "")

    def post(self, request):
        #上传
        file_obj = request.FILES.get('file')
        #生成图片id
        file_uuid = str(uuid.uuid4())
        #名称
        file_type = file_obj.name.split(".")[-1]
        file_name = file_obj.name
        imgPath = file_uuid + "." + file_type

        #上传人
        token_dic, err = ParseToekn(request.META.get('HTTP_AUTHORIZATION'))
        if err != None:
            return response(401, "请重新登录", None)
        username = token_dic['data']['username']

        #保存文件
        with open(f"{path}/{imgPath}", "wb") as f:
            for chunk in file_obj.chunks():
                f.write(chunk)

        #存入数据库
        new_dic = {
            "username": username,
            "file_name": file_name,
            "mid": file_uuid,
            "path": f"{path}/{imgPath}",
        }
        try:
            models.Contract.objects.create(**new_dic)
        except Exception as e:
            return response(503, "图片保存失败", None)
        #返回成功生成的uuid连接
        return response(200, "上传成功", file_uuid)
